import { sleep } from "@/core/tooler";
import * as THREE from "three";

export function getSize(obj: THREE.Object3D) {
    const boundingBox = new THREE.Box3();
    boundingBox.setFromObject(obj);
    const size = new THREE.Vector3();
    boundingBox.getSize(size);
    return size;
}

export function convertToTree(object: THREE.Object3D) {
    const tree = {
        id: object.id,
        type: object.type,
        label: [object.name || "unname", object.id, object.type].join(" "),
        children: [] as any[],
    };

    for (let i = 0; i < object.children.length; i++) {
        const child = object.children[i];
        const childTree = convertToTree(child);
        tree.children.push(childTree);
    }

    return tree;
}

export async function alignMesh(obj: THREE.Mesh) {
    obj.rotation.set(0, 0, 0);
    obj.position.set(0, 0, 0);
    obj.scale.set(1, 1, 1);
    await sleep(30);
    const boundingBox = new THREE.Box3();
    boundingBox.setFromObject(obj);
    const size = new THREE.Vector3();
    boundingBox.getSize(size);
    console.log(size, boundingBox, "---")
    let cx = (boundingBox.min.x + boundingBox.max.x) / 2;
    let cy = (boundingBox.min.y + boundingBox.max.y) / 2;
    let cz = (boundingBox.min.z + boundingBox.max.z) / 2;
    obj.geometry.translate(0 - cx, 0 - cy, 0 - cz);
    obj.updateMatrix();
    obj.updateMatrixWorld();
}